package _1获取请求信息;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/RequestServlet")
public class RequestServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw = resp.getWriter();
		
		// 设定提交过来编码方式
		req.setCharacterEncoding("utf-8");
		
		// 1. 请求行
		pw.println("<h1>1. 请求行</h1>");
		pw.println("请求的方式:"+req.getMethod());
		
		pw.println("<br>请求的路径:"+req.getRequestURI());// 要用到
		pw.println("<br>请求的路径:"+req.getRequestURL());// 要用到
		
		pw.println("<br>协议:"+req.getProtocol());
		
		// 2. 请求头
		pw.println("<h1>2. 请求头中内容:</h1>");
		// req.getHeader(key) 
		pw.println("浏览器类型User-Agent:"+req.getHeader("User-Agent"));
		
		Enumeration<String> keys = req.getHeaderNames();
		while(keys.hasMoreElements())
		{
			String key = keys.nextElement();
			pw.println(key+":"+req.getHeader(key)+"<br/>");
		}
		
		// 3. 请求体
		
		// 4. 用户提交过来的参数
		// .getParameter(key)   		得到字符串    
		// .getParameterValues(key)		得到字符串数组	（比如是复选框checkbox提交的内容) 
		// 既可以处理get方法 也可以post方法
		// 如果是GET方式 就从网址后面跟的参数中取出
		// 如果是POST方式 就从请求体中取出
		pw.println("<h1>4. 请求的参数</h1>");
//		String username = req.getParameter("username");
//		String password = req.getParameter("password");
//		String[] like = req.getParameterValues("like"); 
//		pw.println("username:"+username+",passowrd:"+password);
		
		// 得到所有参数及值
		// .getParameterMap();
		Map<String,String[]> infos = req.getParameterMap();
		for(Entry<String,String[]> info:infos.entrySet())
		{
			pw.println(info.getKey()+":"+Arrays.toString(info.getValue())+"<br />");
		}
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
	{
		doGet(req, resp);
	}
}